package root.electronclass.electronclass.home.widget;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import root.electronclass.electronclass.common.base.BasicAdapter;
import root.electronclass.electronclass.common.base.BindingHolder;
import root.electronclass.electronclass.databinding.HomeNotifyBinding;
import root.electronclass.electronclass.mvp.GlobalParameter;
import root.electronclass.electronclass.mvp.base.BaseResponse;
import root.electronclass.electronclass.mvp.entity.Class1Dto;
import root.electronclass.electronclass.mvp.entity.HomeNoticeInfoHH;
import root.electronclass.electronclass.mvp.entity.IHomeNoticeInfoH;
import root.electronclass.electronclass.mvp.entity.NoticeIDDto;
import root.electronclass.electronclass.mvp.entity.HomeNoticeInfoH;
import root.electronclass.electronclass.mvp.rest.RestManager;
import root.electronclass.electronclass.MainActivity;
import root.electronclass.electronclass.R;
import root.electronclass.electronclass.databinding.HomeItemNoticeBinding;
import root.electronclass.electronclass.databinding.HomeNoticeInfoBinding;
import root.electronclass.electronclass.grade.notice.ClassNotificationFragment;
import root.electronclass.electronclass.other.WebFragment;
import root.electronclass.electronclass.school.SchoolNotificationFragment;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeNoticeView {
    private static final String TAG = "HomeNoticeView";

    private Context context;
    private HomeNotifyBinding binding;

    private List<String> typeList;

    private String curType;

    {
        typeList = new ArrayList<>();
        typeList.add("校园");
        typeList.add("班级");
    }


    public HomeNoticeView(Context context, ViewGroup view) {
        this.binding = HomeNotifyBinding.bind(view);
        this.context = context;
        init();
    }

    private BasicAdapter<IHomeNoticeInfoH, HomeItemNoticeBinding> adapter = new BasicAdapter<IHomeNoticeInfoH, HomeItemNoticeBinding>() {
        @Override
        public void onBindViewHolder(@NonNull BindingHolder<HomeItemNoticeBinding> holder, @Nullable IHomeNoticeInfoH item) {
            holder.getBinding().tvNoticeTitle.setText(item.getTitleH());
            holder.getBinding().tvDate.setText(item.getDateH());
            holder.getBinding().imgNotice.setImageURI(item.getNoticeUrl());
            holder.getBinding().tvLevel.setText(item.getLevelH() == 0 ? "普通" : (item.getLevelH() == 1 ? "重要" : "全屏"));
            holder.getBinding().imgState.setBackgroundResource(item.getStatusH() == 1 ? R.drawable.bg_home_item_notice_read : R.drawable.bg_home_item_notice_noread);
            holder.getBinding().imgState.setText(item.getStatusH() == 1 ? "已读" : "未读");
            holder.getBinding().imgState.setTextColor(item.getStatusH() == 1 ? context.getResources().getColor(R.color.c_888888) : context.getResources().getColor(R.color.c_FF503D) );
            final IHomeNoticeInfoH infoH  = item;
            holder.getBinding().getRoot().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateState(infoH);
                    String url = "0".equals(curType) ? WebFragment.SCHOOL_NOTIFICATION : WebFragment.CLASS_NOTIFICATION;
                    WebFragment.startWeb((FragmentActivity) context, String.format(url, infoH.getNoticeIdH()));
                }
            });
        }

        @Override
        public void onBindViewHolder(@NonNull BindingHolder<HomeItemNoticeBinding> holder, int position) {
            super.onBindViewHolder(holder, position);

        }
    };

    private void init() {
        binding.tabSelector.initData(typeList);
        binding.tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity fragmentActivity = ((MainActivity)context);
                Bundle bundle = new Bundle();
                if ("0".equals(curType) ) {
                    bundle.putSerializable("TARGET_SCHOOL", SchoolNotificationFragment.class);
                    fragmentActivity.selectPage(MainActivity.Page.SCHOOL, bundle);
                } else {
                    bundle.putSerializable("TARGET_CLASS", ClassNotificationFragment.class);
                    fragmentActivity.selectPage(MainActivity.Page.CLASS, bundle);
                }
            }
        });
        binding.tabSelector.setOnTabChangedListener(index -> {
            if (index == 0) {
                request0();
            } else {
                request1();
            }
        });
        request0();
    }




    public void request0() {
        curType = "0";
        long id = GlobalParameter.getEcardInfo().getClassId();
        String sid = GlobalParameter.getSchoolInfo().getSchoolId();
        Class1Dto dto = new Class1Dto();
        dto.setDepartId(String.valueOf(id));
        dto.setSchoolId(sid);
        dto.setDateType("2");
        RestManager.getInstance().initRest().noticeList(dto).enqueue(new Callback<BaseResponse<List<HomeNoticeInfoH>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<HomeNoticeInfoH>>> call, Response<BaseResponse<List<HomeNoticeInfoH>>> response) {
                if (!TextUtils.equals("0", curType)) {
                    return;
                }
                if (response.isSuccessful()) {
                    List<HomeNoticeInfoH> list = response.body().getRows();
                    if (list != null && list.size() > 0) {
                        HomeNoticeInfoH noticeInfoH = list.get(0);
                        binding.rvNotice.setVisibility(View.VISIBLE);
                        LinearLayoutManager manager = new LinearLayoutManager(context, RecyclerView.VERTICAL, false);
                        binding.rvNotice.setLayoutManager(manager);
                        adapter.replaceAll(list);
                        binding.rvNotice.setAdapter(adapter);

                        binding.getRoot().setTag(noticeInfoH.getNoticeIdH());
                    }else {
                        showEmpty();
                    }
                } else {
                    showEmpty();
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<List<HomeNoticeInfoH>>> call, Throwable t) {
                showEmpty();
            }
        });
    }

    private void showEmpty() {
        binding.getRoot().setTag(null);
        adapter.replaceAll(new ArrayList<>());
    }


    public void request1() {
        curType = "1";
        long id = GlobalParameter.getEcardInfo().getClassId();
        RestManager.getInstance().initRest().noticeListClass(String.valueOf(id)).enqueue(new Callback<BaseResponse<List<HomeNoticeInfoHH>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<HomeNoticeInfoHH>>> call, Response<BaseResponse<List<HomeNoticeInfoHH>>> response) {
                if (!TextUtils.equals("1", curType)) {
                    return;
                }
                if (response.isSuccessful()) {
                    List<HomeNoticeInfoHH> list = response.body().getRows();
                    if (list != null && list.size() > 0) {
                        HomeNoticeInfoHH noticeInfoH = list.get(0);
                        binding.rvNotice.setVisibility(View.VISIBLE);
                        LinearLayoutManager manager = new LinearLayoutManager(context, RecyclerView.VERTICAL, false);
                        binding.rvNotice.setLayoutManager(manager);
                        adapter.replaceAll(list);
                        binding.rvNotice.setAdapter(adapter);

                        binding.getRoot().setTag(noticeInfoH.getNoticeIdH());
                    }else {
                        showEmpty();
                    }
                } else {
                    showEmpty();
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<List<HomeNoticeInfoHH>>> call, Throwable t) {
                showEmpty();
            }
        });
    }

    public void refresh() {
        if ("1".equals(curType)) {
            request1();
        } else {
            request0();
        }
    }


    private void updateState(IHomeNoticeInfoH info) {
        NoticeIDDto dto = new NoticeIDDto();
        dto.setNoticeId(info.getNoticeIdH());
        dto.setId(info.getIdH());
        RestManager.getInstance().initRest().updateNotice(dto).enqueue(new Callback<BaseResponse<Object>>() {
            @Override
            public void onResponse(Call<BaseResponse<Object>> call, Response<BaseResponse<Object>> response) {
                if(response != null && response.body() != null &&  response.body().isSuccess()) {
                    info.setStatusH(1);
                    adapter.notifyDataSetChanged();
                    if (binding.getRoot().getTag() != null &&
                             (binding.getRoot().getTag()) == info.getNoticeIdH()) {
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<Object>> call, Throwable t) {

            }
        });
    }


}
